<template>
    <!-- 靠右搜索框 -->
    <div class="search-input-container">
        <div style="width: 30%; height:5%;display: flex; align-items: center;position: absolute;right: 5px;">
            <el-input v-model="search_input" class="search-input" placeholder="搜索内容..." @keyup.enter="searchBlog()" />
            <el-icon style="width: 8%; height: auto;" @click="searchBlog()">
                <Search style="color: black;" />
            </el-icon>
        </div>
    </div>
    <!-- 主体容器 -->
    <div class="result-container">
        <!-- 搜索结果 -->
        <div class="search-result">
            <div class="result-header" style="margin-bottom: 15px;">搜索到{{ articles.length }}条结果</div>
            <div v-for="(article, index) in articles" :key="index" class="result">
                <div style="display: flex; justify-content: space-between;">
                    <span class="article-title" v-html="highlightTitleText(article.title, search)"
                        @click="toBlog(index)"></span>
                    <span
                        class="article-author-time">{{ article.author }}&nbsp;&nbsp;{{ formatTime(article.date) }}&nbsp;&nbsp;
                        <el-popconfirm title="确认要删除这篇博文?" cancel-button-text="取消" confirm-button-text="确认"
                            @confirm="deleteBlogById(article.id)"><template #reference>
                                <el-button size="small" type="danger">
                                    删除
                                </el-button>
                            </template></el-popconfirm></span>
                </div>
                <div @click="toBlog(index)">
                    <span class="article-content">
                        <el-text line-clamp="2" v-html="highlightContentText(article.content, search)"></el-text>
                    </span>
                </div>
                <el-divider style="margin: 15px 0% 15px 0%; width: 100%;" />
            </div>
        </div>
        <!-- 筛选器 -->
        <div class="filter-container">
            <h4 class="filter-title">筛选</h4>
            <el-divider style="margin:0%" />
            <h4 class="filter-title">类型</h4>
            <el-radio-group v-model="radio_type" style="margin-left: 5%;">
                <el-radio-button value="1" @click="searchAll">全部</el-radio-button>
                <el-radio-button value="2" @click="searchByTitle">标题</el-radio-button>
                <el-radio-button value="3" @click="searchByContent">内容</el-radio-button>
            </el-radio-group>
            <el-divider style="margin: 20px 0% 0% 0%; width: 100%;" />
            <h4 class="filter-title">作者</h4>
            <el-input v-model="author_input" class="search-input" placeholder="搜索作者..." @keyup.enter="doSearch" />
            <el-divider style="margin: 20px 0% 0% 0%; width: 100%;" />
            <h4 class="filter-title">博文ID</h4>
            <el-input v-model="id_input" class="search-input" placeholder="通过博文ID搜索..." @keyup.enter="searchById" />
        </div>
    </div>
    <div>

    </div>
</template>

<script lang="ts" setup>
    import {
        getBlogByTitle,
        getUserById,
        getBlogByContent,
        listBlogById,
        deleteBlog,
    } from '@/api'
    import {
        Search
    } from '@element-plus/icons-vue'
    import {
        all
    } from 'axios';
    import {
        ElMessage
    } from 'element-plus';
    import {
        ref,
    } from 'vue';

    const search_input = ref('');
    const author_input = ref('');
    const id_input = ref('');
    const radio_type = ref('1');
    const search = getUrlParam('word');
    const tempArticles = ref([]);
    const articles = ref([]);

    function getUrlParam(key: string) {

        // 获取地址栏上"?"问号及后面的参数
        let search = window.location.search.substring(1);
        console.log('search：', search);

        // 将url参数转为url对象
        let urlsp = new URLSearchParams(search);
        console.log('URLSearchParams', urlsp);

        // 根所传入的key返回对应的参数值
        return urlsp.get(key);
    }

    search_input.value = getUrlParam('word');
    const formatTime = (timestamp: number) => {
        const date = new Date(timestamp);
        return date.toLocaleString();
    }

    const toBlog = (index: number) => {
        window.location.href = "http://localhost:8080/adminSeeBlog?id=" + articles.value[index].id;
    }

    const searchBlog = () => {
        window.location.href = 'http://localhost:8080/adminSearch?word=' + search_input.value;
    }

    const searchAll = () => {
        let used = [];
        tempArticles.value = [];
        articles.value = [];
        getBlogByTitle(getUrlParam('word')).then(
            res => {
                for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].status == 2) {
                        tempArticles.value.push(res.data[i])
                        used[res.data[i].id] = true;
                    }
                }
                getBlogByContent(getUrlParam('word')).then(
                    res => {
                        for (let i = 0; i < res.data.length; i++) {
                            console.log("used[" + res.data[i].id + "]=" + used[res.data[i].id]);
                            if (res.data[i].status == 2 && (used[res.data[i].id] == undefined || used[
                                    res.data[i].id] == false)) {
                                tempArticles.value.push(res.data[i]);
                            }
                        }
                        for (let i = 0; i < tempArticles.value.length; i++) {
                            getUserById(tempArticles.value[i].bloggerId).then(
                                rq => {
                                    tempArticles.value[i].author = rq.data.nickname;
                                    if (author_input.value == '') articles.value.push(tempArticles
                                        .value[i]);
                                    else if (tempArticles.value[i].author.includes(author_input.value))
                                        articles.value.push(tempArticles.value[i]);
                                }
                            )
                        }

                    }
                )
            }
        )
    }

    const searchByTitle = () => {
        tempArticles.value = [];
        articles.value = [];
        getBlogByTitle(getUrlParam('word')).then(
            res => {
                for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].status == 2) {
                        tempArticles.value.push(res.data[i]);
                    }
                }
                for (let i = 0; i < tempArticles.value.length; i++) {
                    getUserById(tempArticles.value[i].bloggerId).then(
                        rq => {
                            tempArticles.value[i].author = rq.data.nickname;
                            if (author_input.value == '') articles.value.push(tempArticles.value[i]);
                            else if (tempArticles.value[i].author.includes(author_input.value)) articles
                                .value.push(tempArticles.value[i]);
                        }
                    )
                }
            }
        )
    }

    const searchByContent = () => {
        tempArticles.value = [];
        articles.value = [];
        getBlogByContent(getUrlParam('word')).then(
            res => {
                for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].status == 2) {
                        tempArticles.value.push(res.data[i]);
                    }
                }
                for (let i = 0; i < tempArticles.value.length; i++) {
                    getUserById(tempArticles.value[i].bloggerId).then(
                        rq => {
                            tempArticles.value[i].author = rq.data.nickname;
                            if (author_input.value == '') articles.value.push(tempArticles.value[i]);
                            else if (tempArticles.value[i].author.includes(author_input.value)) articles
                                .value.push(tempArticles.value[i]);
                        }
                    )
                }
            }
        )
    }

    searchAll();

    const escapeRegExp = (string: string) => string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

    const highlightTitleText = (text: string, keyword: string) => {
        if (!keyword) return text;
        const regex = new RegExp(escapeRegExp(keyword), 'gi');
        const highlighted = text.replace(regex, (match) => `<span style="color:red;">${match}</span>`);
        console.log(highlighted);
        return highlighted;
    }

    const highlightContentText = (text: string, keyword: string) => {
        if (!keyword) return text;
        const regex = new RegExp(escapeRegExp(keyword), 'gi');
        console.log(keyword);
        const highlighted = text.replace(regex, (match) => `<el-text style="color:red;">${match}</el-text>`);
        console.log(highlighted);
        return highlighted;
    }

    const doSearch = () => {
        if (radio_type.value == "1") searchAll();
        if (radio_type.value == "2") searchByTitle;
        if (radio_type.value == "3") searchByContent;
    }

    const searchById = () => {

        if (id_input.value == "") {
            searchAll();
            return;
        }

        listBlogById(id_input.value).then(
            res => {
                articles.value = [];
                if (res.data != null) {
                    articles.value.push(res.data);
                    getUserById(articles.value[0].bloggerId).then(
                        res => {
                            articles.value[0].author = res.data.nickname;
                        }
                    )
                    ElMessage({
                        message: "找到博客: ID = " + id_input.value,
                        type: "success",
                    });
                } else ElMessage({
                    message: "没有找到该博客: ID = " + id_input.value,
                    type: "error",
                });
            }
        )
    }
    const deleteBlogById = (id: any) => {
        deleteBlog(id).then(
            res => {
                if (res.code === 200) {
                    ElMessage({
                        message: "删除博客成功,2秒后跳转",
                        type: "success",
                    });
                    articles.value.splice(0, 1);
                    setTimeout(() => {
                        location.reload();
                    }, 2000);
                } else ElMessage({
                    message: "删除博客失败",
                    type: "error",
                });
            }
        )
    }
</script>

<style scoped>
    .search-input-container {
        height: 80px;
        width: 100%;
        display: flex;
        align-items: center;
    }

    .search-input {
        width: 80%;
        margin-left: 15px;
        height: 40px;
    }

    .result-container {
        display: flex;
        width: 100%;
        height: 709px;
    }

    .search-result {
        width: 80%;
        height: 100%;
        box-shadow: 0 0 1px 0 #000;
        /* display: flex; */
    }

    .result-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-weight: 600;
        width: 50%;
        margin-left: 20%;
        margin-top: 10px;
        margin-bottom: 10px;
    }

    .result {
        width: 70%;
        margin-left: 20%;
    }

    .article-title {
        font-size: larger;
        font-weight: 600;
    }

    .article-author {
        font-size: medium;
        font-weight: 500;
    }

    .filter-container {
        width: 20%;
        height: 100%;
        margin-left: 5px;
        box-shadow: 0 0 1px 0 #000;
    }

    .filter-title {
        margin: 5%;

    }

    .highlight {
        color: red !important;
        font-size: larger;
        font-weight: 600;
    }
</style>